import 'dart:io';

import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:fate_blind_box/utils/assets.dart';
import 'package:fate_blind_box/utils/provider.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

import '../../../network/Api.dart';
import '../../../utils/loading.dart';
import '../../../utils/snack_bar.dart';
import 'package:universal_html/html.dart' as html;
//个人简介
class registerInstitionUI extends StatefulWidget {
  final String introduce;

  registerInstitionUI(this.introduce, {Key? key}) : super(key: key);

  @override
  State<registerInstitionUI> createState() => _registerInstitionState();
}

class _registerInstitionState extends State<registerInstitionUI> {

  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _xinyongController = TextEditingController();
  final TextEditingController _addressController = TextEditingController();
  String licensePic = '';

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

  }

  // 修改个人简介
  _getUserinfo() async {

    final res = await Api.getInstance().ModifyMeIntroduce(Provider.memberId,_nameController.text);
    final data = res['msg'];
    ThemeSnackBar.show(context, data);
    Navigator.of(context).pop();
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    return Scaffold(
      appBar: AppBar(

        title: const Text('商家注册',style: TextStyle(color: Colors.black,fontSize: 16),),
        elevation: 0,

        // actions: <Widget>[
        //   Container(
        //     margin: const EdgeInsets.only(right: 15,top: 10,bottom: 10),
        //     height: 31,
        //     child: TextButton(
        //       style: TextButton.styleFrom(
        //         backgroundColor: ThemeColor.appColor,
        //         shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5)),
        //         textStyle: const TextStyle(color: Colors.white),
        //       ),
        //
        //       child: const Text('完成',style: TextStyle(color: Colors.white),),
        //
        //       onPressed: () {
        //         _getUserinfo();
        //       },
        //     ),
        //   )
        //
        //
        // ],
      ),

      body: Container(
          margin: const EdgeInsets.fromLTRB(15, 14, 15, 0),
          child: SingleChildScrollView(
            child: Column(
              children: [
                Container(
                    alignment: Alignment.centerLeft,
                    child:const
                    Text(
                      '营业执照',
                      style: TextStyle(color: Colors.black,
                        fontSize: 16,
                      ),
                    )
                ),
                const SizedBox(height: 14,),
                GestureDetector(
                  onTap: (){
                    //图片点击事件
                    _selectPhoto(context,size.width);
                  },
                  child: licensePic.isEmpty
                      ? Image.asset(
                    "images/ic_yingyePhoto.png",
                    width: size.width,
                    height: 248,
                    fit: BoxFit.cover,
                  )
                      : Image.file(
                    File(licensePic),
                    width: size.width,
                    height: 248,
                    fit: BoxFit.fill,
                  ),
                ),
                const SizedBox(height: 14,),
                Container(
                    alignment: Alignment.centerLeft,
                    child:const
                    Text(
                      '商家全称',
                      style: TextStyle(color: Colors.black,
                        fontSize: 16,
                      ),
                    )
                ),
                Container(
                  margin: const EdgeInsets.fromLTRB(0, 14, 0, 0),
                  height: 45,
                  child: TextField(
                    controller: _nameController,
                    maxLength: 16,
                    obscureText: false,

                    keyboardType: TextInputType.text,
                    cursorColor: ThemeColor.sendMsgTextColor,
                    style: TextStyle(
                        fontSize: 12,
                        color: ThemeColor.textColor
                    ),
                    onChanged: (value){
                      // setState(() {
                      //   _nameController.text = value;
                      // });
                    },
                    decoration: InputDecoration(
                      hintText: _nameController.text.isEmpty ? "请输入商家全称" : _nameController.text,
                      counterText: "",
                      border: InputBorder.none,
                      hintStyle: TextStyle(color: ThemeColor.textColorSecond),
                      fillColor: const Color(0xffF1F3FB),
                      filled: true,
                      enabledBorder: const OutlineInputBorder(
                        /*边角*/
                        borderRadius: BorderRadius.all(
                          Radius.circular(5), //边角为30
                        ),
                        borderSide: BorderSide(
                          color: Colors.white54, //边线颜色为黄色
                          width: 1, //边线宽度为2
                        ),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(5),
                        borderSide: const BorderSide(
                          color: Colors.white54, //边框颜色为绿色
                          width: 1, //宽度为5
                        ),

                      ),
                      contentPadding: const EdgeInsets.only(
                          top: 0,
                          bottom: 0,
                          left: 10
                      ),
                    ),
                  ),
                ),
                const SizedBox(height: 14,),
                Container(
                    alignment: Alignment.centerLeft,
                    child:const
                    Text(
                      '统一社会信用代码',
                      style: TextStyle(color: Colors.black,
                        fontSize: 16,
                      ),
                    )
                ),
                Container(
                  margin: const EdgeInsets.fromLTRB(0, 14, 0, 0),
                  height: 45,
                  child: TextField(
                    controller: _xinyongController,
                    maxLength: 16,
                    obscureText: false,

                    keyboardType: TextInputType.text,
                    cursorColor: ThemeColor.sendMsgTextColor,
                    style: TextStyle(
                        fontSize: 12,
                        color: ThemeColor.textColor
                    ),
                    onChanged: (value){
                      // setState(() {
                      //   _xinyongController.text = value;
                      // });
                    },
                    decoration: InputDecoration(
                      hintText: _xinyongController.text.isEmpty ? "请输入统一社会信用代码" : _xinyongController.text,
                      counterText: "",
                      border: InputBorder.none,
                      hintStyle: TextStyle(color: ThemeColor.textColorSecond),
                      fillColor: const Color(0xffF1F3FB),
                      filled: false,
                      enabledBorder: const OutlineInputBorder(
                        /*边角*/
                        borderRadius: BorderRadius.all(
                          Radius.circular(5), //边角为30
                        ),
                        borderSide: BorderSide(
                          color: Colors.white54, //边线颜色为黄色
                          width: 1, //边线宽度为2
                        ),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(5),
                        borderSide: const BorderSide(
                          color: Colors.white54, //边框颜色为绿色
                          width: 1, //宽度为5
                        ),

                      ),
                      contentPadding: const EdgeInsets.only(
                          top: 0,
                          bottom: 0,
                          left: 10
                      ),
                    ),
                  ),
                ),
                const SizedBox(height: 14,),
                Container(
                    alignment: Alignment.centerLeft,
                    child:const
                    Text(
                      '注册地址',
                      style: TextStyle(color: Colors.black,
                        fontSize: 16,
                      ),
                    )
                ),
                Container(
                  margin: const EdgeInsets.fromLTRB(0, 14, 0, 0),
                  height: 45,
                  child: TextField(
                    controller: _addressController,
                    maxLength: 16,
                    obscureText: false,

                    keyboardType: TextInputType.text,
                    cursorColor: ThemeColor.sendMsgTextColor,
                    style: TextStyle(
                        fontSize: 12,
                        color: ThemeColor.textColor
                    ),
                    onChanged: (value){
                      // setState(() {
                      //   _addressController.text = value;
                      // });
                    },
                    decoration: InputDecoration(
                      hintText: _addressController.text.isEmpty ? "请输入注册地址" : _addressController.text,
                      counterText: "",
                      border: InputBorder.none,
                      hintStyle: TextStyle(color: ThemeColor.textColorSecond),
                      fillColor: const Color(0xffF1F3FB),
                      filled: true,
                      enabledBorder: const OutlineInputBorder(
                        /*边角*/
                        borderRadius: BorderRadius.all(
                          Radius.circular(5), //边角为30
                        ),
                        borderSide: BorderSide(
                          color: Colors.white54, //边线颜色为黄色
                          width: 1, //边线宽度为2
                        ),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(5),
                        borderSide: const BorderSide(
                          color: Colors.white54, //边框颜色为绿色
                          width: 1, //宽度为5
                        ),

                      ),
                      contentPadding: const EdgeInsets.only(
                          top: 0,
                          bottom: 0,
                          left: 10
                      ),
                    ),
                  ),
                ),
                // Expanded(child: Container()),
                Padding(

                    // padding: const EdgeInsets.only(bottom: 28.0),
                    padding: const EdgeInsets.only(top: 28.0),
                    child: GestureDetector(
                      onTap: (){
                        _submit();
                      },
                      child: Container(
                          height: 44,
                          margin: const EdgeInsets.symmetric(
                              horizontal: 12, vertical: 24),
                          decoration: ShapeDecoration(
                              shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(22)
                              ),
                              color: ThemeColor.appColor
                          ),
                          alignment: Alignment.center,
                          child: const Text(
                            "完成", style: TextStyle(color: Colors.white),)

                      ),
                    )



                )


              ],
            ),
          )
      ),
    );
  }

  bool _verity() {
    if(licensePic.isEmpty){
      toast('请上传营业执照');
      return false;
    }
    if(_nameController.text.isEmpty){
      toast('请填写商家全称');
      return false;
    }
    if(_xinyongController.text.isEmpty){
      toast('请填写统一社会信用代码');
      return false;
    }
    if(_addressController.text.isEmpty){
      toast('请填写注册地址');
      return false;
    }
    return true;
  }

  void _submit(){
    if(!_verity()){
      return;
    }

    print('rrr ${_nameController.text} ${_xinyongController.text} ${_addressController.text}');
    loading(() async{
      final res = await Api.getInstance().verifyLicense(
          _nameController.text,
          _xinyongController.text,
          _addressController.text,
      );
      final data = res['msg'];
      // ThemeSnackBar.show(context, data);
      toast(data);
      if(res['code'] == 0){
        Navigator.of(context).pop(true);
      }
    });
  }

  Future<void> _selectPhoto(context, double width) async {
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return SizedBox(
            height: 220.0,
            child: Container(
                alignment: Alignment.center,
                child: Column(
                  children: [

                    GestureDetector(
                        onTap: () {
                          _checkAvatar('拍照');
                        },
                        child: Container(
                          alignment: Alignment.center,
                          width: width,
                          height: 55,
                          color: Colors.white,
                          child: const Text('拍照'),
                        )
                    ),
                    Divider(color: ThemeColor.sendMsgColor, height: 1,),
                    GestureDetector(
                        onTap: () {
                          _checkAvatar('相册');
                        },
                        child: Container(
                          alignment: Alignment.center,
                          width: width,
                          height: 60,
                          color: Colors.white,
                          child: const Text('从手机相册选择'),
                        )
                    ),
                    Divider(
                      color: ThemeColor.sendMsgColor, thickness: 7, height: 1,),
                    GestureDetector(
                        onTap: () {
                          Navigator.pop(context);
                        },
                        child: Container(
                          alignment: Alignment.center,
                          width: width,
                          height: 55,
                          child: const Text('取消'),
                        )
                    )

                  ],
                )
            )
        );
      },
    );
  }

  /// 头像
  _checkAvatar(String type) {
    Navigator.pop(context);
    ImageSource source;
    if(type == '拍照'){
      source = ImageSource.camera;
    }else {
      source = ImageSource.gallery;
    }
    if (!kIsWeb) {
      loading(() async {
        final picker = ImagePicker();
        final pickerFile = await picker.pickImage(source: source);
        if (pickerFile != null) {
          final res = await Api.getInstance().uploadLicense(pickerFile.path); //pickerFile.path
          print('xxx  $res');
          if (res['code'] == 0) {
            // ThemeSnackBar.show(context, res['msg']);
            toast(res['msg']);
            setState(() {
              licensePic = pickerFile.path;
              _nameController.text = res['data']['companyName'];
              _xinyongController.text = res['data']['creditCode'];
              _addressController.text = res['data']['businessAddress'];
            });
          } else {
            ThemeSnackBar.show(context, res['msg']);
          }
        }

      });
    } else {
      final uploadInputElement = html.FileUploadInputElement();
      uploadInputElement.multiple = false;
      uploadInputElement.draggable = true;
      uploadInputElement.click();
      uploadInputElement.onChange.listen((event) {
        final file = uploadInputElement.files?.first;
        if (file != null) {
          loading(() async {
            final formData = html.FormData();
            formData.appendBlob("avatarfile", file.slice(), file.name);
            formData.append("memberId", Provider.memberId);
            Api.getInstance().uploadAvatarFromHtml(formData, (e) {
              if (e['code'] == 0) {
                setState(() {
                  // _user['profilePhoto'] = e['data']['url'];
                });
              } else {
                ThemeSnackBar.show(context, e['msg']);
              }
            });
          });
        }
      });
    }
  }
}